<?php

namespace app\admin\controller\subject\teacher;

use app\common\controller\Backend;
use app\common\library\util\MyWebSocketServer;
use app\common\model\Subject\Teacher\Follow;
use app\common\model\Subject\Teacher\Teacher as TeacherTeacher;
use Exception;
use fast\Http;
use fast\Random;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
/**
 * 课程名师管理
 *
 * @icon fa fa-circle-o
 */
class Teacher extends Backend
{

    /**
     * Teacher模型对象
     * @var \app\admin\model\subject\teacher\Teacher
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new TeacherTeacher();

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function randadd()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        
         
        $params = $this->randTeacher();
        halt($params);
        // $params = $this->request->post('row/a');
        // if (empty($params)) {
        //     $this->error(__('Parameter %s can not be empty', ''));
        // }
        // $validate = [
        //     [
        //         'addnumber'=>['require','integer','>:0','<=:10']
        //     ],
        //     [
        //         'addnumber.require'=>'数量不能为空',
        //         'addnumber.integer'=>'数量需为整数',
        //         'addnumber.>:0'=>'数量需大于零',
        //         'addnumber.<=:0'=>'数量不能超过十个',
        //     ]
        // ];
        // $result = false;
        // Db::startTrans();
        // try {
        //     $this->validateFailException()->validate($params,...$validate);
        //     $paramsList = [];
        //     foreach(range(1,$params['addnumber']) as $number)
        //     {
        //         $params = $this->randTeacher();
        //         //是否采用模型验证
        //         if ($this->modelValidate) {
        //             $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
        //             $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
        //             // $this->model->validateFailException()->validate($validate);
        //             $this->validateFailException()->validate($params,$validate);
        //         }
        //         $params['password'] = md5(md5($params['password']) . $params['salt']);
        //         $paramsList[] = $params;
        //     }
        //     // halt($paramsList);
        //     $result = $this->model->allowField(true)->saveAll($paramsList);
        //     $dataReceive = [];
        //     $adminid = $this->auth->id;
        //     if($result!==false){
        //         foreach ($result as $item){
        //             // 打印每条数据的ID
        //             $busid = $item['id'];
        //             $dataReceive[] = [
        //                 'applyid'=>$adminid,
        //                 'status'=>'apply',
        //                 'busid'=>$busid,
        //             ];
        //         }
        //     }
        //     Db::commit();
        // } catch (ValidateException|PDOException|Exception $e) {
        //     Db::rollback();
        //     $this->error($e->getMessage());
        // }
        // if ($result === false) {
        //     $this->error(__('No rows were inserted'));
        // }
        // $this->success();
    }
    private function randomChineseChar() {
        $start = 0x4E00; // 中文字符开始的Unicode编码
        $end = 0x9FA5; // 中文字符结束的Unicode编码
    
        // 随机生成一个中文字符的Unicode编码
        $unicode = rand($start, $end);
    
        // 将Unicode编码转换为字符
        return mb_convert_encoding(pack('n', $unicode), 'UTF-8', 'UTF-16');
    }
    private function randAvatar($type,$params=[])
    {
        $avatarPath = '/' . 'uploads' . '/' . date('Ymd',time());
        $avatar = $avatarPath . '/' . Random::alnum(32) . '.jpg';
        $avatarPath = ROOT_PATH . 'public' . $avatarPath;
        $avatarFile =  ROOT_PATH . 'public' . $avatar;
        if (!file_exists($avatarPath)) {
            mkdir($avatarPath, 0777, true);
        }
        if($type=='xjh')
        {
            $randImageUrl = 'https://img.xjh.me/random_img.php?return=json';
            $response = Http::get($randImageUrl);
            $response = json_decode($response, true);
            $imageUrl = 'https:'.$response['img'];

            $imageData = Http::get($imageUrl);
            file_put_contents($avatarFile, $imageData);
        }else if($type=='qq')
        {
            $qq = $params['qq'];
            $imageUrl = 'http://q1.qlogo.cn/g?b=qq&nk='.$qq.'&s=640';
            // 初始化cURL会话
            $ch = curl_init();
            
            // 设置cURL选项
            curl_setopt($ch, CURLOPT_URL, $imageUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            
            // 执行cURL会话
            $imageData = curl_exec($ch);
            // 关闭cURL会话
            curl_close($ch);
            // 指定本地文件路径
            
            // 将图片数据写入到本地文件
            file_put_contents($avatarFile, $imageData);
        }
        return $avatar;
    }
    private function randTeacher()
    {
        $params = [];
        //名称
        require_once(ROOT_PATH . 'application\\common\\library\\util\\firstname.php');
        $nameLength = random_int(1,2);
        $allNum = 597;
        $name = $firstname[random_int(0,100)];
        for($n=0;$n<$nameLength;$n++){
            $name .= $this->randomChineseChar();
        }
        $params['name'] = $name;

        //头像
        // $qq = "";
        // for($n=0;$n<9;$n++){
        //     $qq = random_int(0,9).$qq;
        // }
        // $qq = random_int(1,3).$qq;
        // $params['avatar'] = $this->randAvatar('qq',['qq'=>$qq]);
        
        //职位
        $cityUrl = 'https://www.zhipin.com/wapi/zpCommon/data/cityGroup.json';
        $response = Http::get($cityUrl);
        $response = json_decode($response, true);
        $cityGroup = $response['zpData']['cityGroup'];
        $cityList = $cityGroup[array_rand($cityGroup)]['cityList'];
        $city = $cityList[array_rand($cityList)]['code'];

        $districtUrl = 'https://www.zhipin.com/wapi/zpgeek/businessDistrict.json';
        $response = Http::get($districtUrl,['cityCode'=>$city]);
        $response = json_decode($response, true);
        $districtList = $response['zpData']['businessDistrict'];
        $district = $districtList['code'];
        $districtList = $districtList['subLevelModelList'];
        $area = $districtList[array_rand($districtList)]['code'];
        $jobUrl = 'https://www.zhipin.com/web/geek/job?cityCode='.$city.'&areaBusiness='.$district.':'.$area;
        
        $jobUrl = 'https://www.zhipin.com/wapi/zpgeek/search/joblist.json?';
        
        $params = [
            'scene'=> '1',
            'query'=> null,
            'city'=> '101280100',
            'experience'=> null,
            'payType'=> null,
            'partTime'=> null,
            'degree'=> null,
            'industry'=> null,
            'scale'=> null,
            'stage'=> null,
            'position'=> null,
            'jobType'=> null,
            'salary'=> null,
            'multiBusinessDistrict'=> '440103:49129854',
            'multiSubway'=> null,
            'page'=> '1',
            'pageSize'=> '30',
        ];
        $options = [
            CURLOPT_HTTPHEADER=>[
                'Cookie:'.'__zp_stoken__=0149fw5HCjTMQPg4RGsKJHHnDhWDCg3Vsf8OHwo1ObWZswr9Uw4jDhsKlw4ptw4rDhmtWwrppw4zCklnCmFHCnlHCvWbCpcKzwrNdw7HCoMKww4nCq8Sgw7XChsSzw53CtsOEwqpFNRIUEhAYEA4QEhrCh8KFGBoSDhAOFBwZGxkfF0E4xILDj8KJQz5PQDZdX10OUmppUm1WFGNVUUg+FGxlET46QkBIQsONfMOCw7DDj3rDgMO4w4F8w4NCQEBCRMODwro/NcOBUhTDjSMQw4NiHMOCwpwOw4UuDsOUbTjCo8OMw4HDjzxKQMOExYVJTSRKQ0VDQ0FKRU00QTfDkGM6wq/DjMOCHDNEI01NQ0ZBRU1DSENLOUNJwoMzTUI0TxYVHRwcMj7CvjvDgsOjTUM=;'
            ]
        ];
        //test
        $response = json_decode(Http::get($jobUrl,$params),true);
        if($response['code']==37){
            $server = IoServer::factory(
                new HttpServer(
                    new WsServer(
                        new MyWebSocketServer($response['zpData']['seed'],$response['zpData']['ts'])
                    )
                ),
                8080,'127.0.0.1'
            );
            $server->run();
            
        }        
        return $response;
        return $params;
    }
    public function follow($ids=null)
    {
        $this->request->filter(['strip_tags', 'trim']);
        // halt($this->request->get());
        $this->model = new Follow();
        //设置过滤方法
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $whereFollow = ['teacher.id'=>$ids];
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['teacher','business'])
            ->where($whereFollow)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        // halt($where);
        return json($result);
    }
}